import { changeContainerStatusReq, listContainerReq } from '@/api/docker'
import deleteImage from '@/assets/competition/delete.png'
import linuxImage from '@/assets/competition/linuxImage.png'
import masterimg from '@/assets/instance/master.png'
import cunchuimg from '@/assets/instance/用户储存.png'

import panel from '@/assets/instance/已启动课程.png'
import startimg from '@/assets/instance/启动实例.png'
import stoptimg from '@/assets/instance/停止实例.png'
import reflushimg from '@/assets/instance/刷新实例.png'


import hostPanel from '@/assets/competition/panelHost.png'
import { DeleteOneSessionDocument,useMyInfoQuery,useDeleteOneSessionMutation,DeleteOneSessionInput, Document, MyInfoDocument} from '@/generated/graphql'
import { urqlOptions } from '@/plugins/urql'
import { useClient } from '@urql/vue'
import { Session_store } from '@/stores/session'

import { Route } from '@/router'
import { useUserStore } from '@/stores/auth'
import { useDockerApiPath } from '@/stores/dockerApi'
import { useCourseSessionStore } from '@/stores/useCourseStore'
import { getExtends } from '@/utils/common'
import { DLog } from '@/utils/log'
import { createClient } from '@urql/vue'
import { message, Modal} from 'ant-design-vue'

import { TabsProps } from 'ant-design-vue/es/tabs';
import { head } from 'lodash-es'
import { defer, forkJoin, from, lastValueFrom, mergeMap, of } from 'rxjs'
import { computed, defineComponent,watch,watchEffect ,ref,onMounted,nextTick, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import {OpenstackServices} from "@/hooks/services/openstackServices";
export default defineComponent({
  setup(_props) {
    const { t } = useI18n()
    const userStore = useUserStore()
   const use_client = useClient()

    const client = createClient(urqlOptions)
    const data = reactive<{
      document?: Document
      container?: any
      currentExtends?: any
      selectHostname?: string
    }>({ document: undefined })
    //我改后
    const tabPosition = ref<TabsProps['tabPosition']>('left');
    const activeKey = ref('1');
    const session_store=Session_store()
    const me = useMyInfoQuery();
    const session =  ref<any>();
    onMounted(async () => {
      await me.data.value?.me;
    });
    let session_platformType: string
    watchEffect(async () => {
      if (me.data.value) {
        session.value = me.data.value.me;
        await nextTick();
        console.log(session.value);
        data.document=session.value.session.document
 session_platformType=session.value?.session?.instances[0].platformType
    //  console.log(session_platformType);
    if(!session.value?.session){
      console.log("没有session");
      session_store.$state.isshow=false
    }else{
      console.log("有session");
      
    }
     
      }
    });
//
    /**
     * 删除容器
     */
    const deleteAllContainer = () => {
      //const containerIds = data.container.map((c: any) => c.Id)
      Modal.warning({
        title: t('cover.stop_button_tip'),
        content: t('competitionTag.deleteAllContainer'),
        okText: 'ok',
        onOk: async () => {
          from(client.query(MyInfoDocument).toPromise())
            .pipe(
              mergeMap((_me) => {
                const me = _me
                return forkJoin([
                  client
                    .mutation(DeleteOneSessionDocument, {
                      data: {
                        id: me.data?.me?.session?.id,
                        force: true
                      }
                    })
                    .toPromise()
                ])
              })
            )
            .subscribe({
              next: (_) => {
                message.success(t('competitionTag.success'))
               
                router.go(0)
                
              },
              error: () => {
                router.go(0)
              }
            })
        }
      })
    }

    //获取课程信息中的hostname
    const hostname = computed(() => {
      if (data.currentExtends) {
        const backends: any = head(data.currentExtends.backends)
        DLog.Info('competitionTag backends', backends)
        DLog.Info('hostname', backends.hostname)
        return backends.hostname
      }
      return []
    })

    //获取当前选中的容器信息
    const currentSelectContainer = computed(() => {
      DLog.Info('selectHostName', data.selectHostname)
      if (data.selectHostname) {
        DLog.Info('container', data.container)
        const reg = new RegExp('.*(' + data.selectHostname + ')$')
        const _container = data.container.filter((x: any) => reg.test(x.Names[0]))
        DLog.Info('current container', _container[0])
        return _container[0]
      }
      return undefined
    })

    //获取当前用户创建的容器信息
    const openstack_Services=new OpenstackServices(use_client)

    const getUserContainers = async () => {
      const containers$ = defer(() => from(listContainerReq({ label: [`username=${userStore.user?.username}`] })))
      console.log(containers$);
      
      const containers = await lastValueFrom<any>(containers$)
         data.container = containers
      console.log("用户创建的容器信息",data.container);
      
      return containers
    }

    //刷新容器信息
    const refetchContainers = async (showMessage: boolean = true) => {
      await getUserContainers()
      showMessage && message.success(t('competitionTag.refetchSuccess'))
    }

    //启动容器
    const changeContainerState = async (sign: 'start' | 'stop') => {
      console.log(data)
      const containerIds = data.container.map((x: any) => x.Id)
      const startContainers$ = of(containerIds).pipe(
        mergeMap((x) => forkJoin(x.map((_x: string) => changeContainerStatusReq({ id: _x, sign }))))
      )
      await lastValueFrom(startContainers$)
      message.success(t('competition.startSuccess'))
      await refetchContainers(false)
    }

    const dockerApi = useDockerApiPath()
    // 新逻辑
    const courseSessionStore = useCourseSessionStore()
    const main = async () => {
      let document
      //判断实例类型是windos还是liux还是其他
      if (dockerApi.isWindows) {
        console.log("windos");
        
        // 是windows情况,由数据库获取相应的课程章节信息
        const documentId = courseSessionStore.document?.id as string
        document = await courseSessionStore.getDocumentByDocumentId(client, documentId, false)
        console.log(document);
        
      } else {
        console.log("liux");
        
        const containers = await getUserContainers()
        console.log(containers);
        
        const headContainer = head<any>(containers)
        document = await courseSessionStore.getDocumentByDocumentId(client, headContainer.Labels.documentId, false)
      console.log(document);
      
      }

      data.document = document.data.document
      data.currentExtends = getExtends(document.data.document)
      data.selectHostname = data.currentExtends.backends[0].hostname[0]
    }

    main()

    //跳转到content界面
    const router = useRouter()

    const courseActionStore = useCourseSessionStore()
    const gotoChapter = () => {
      courseActionStore.setDocument(data.document as Document)
      data.document && router.push({ name: Route.CHAPTER })
    }

    //获取IP地址
    const getIPAddress = (networkSettings: Record<string, any>) => {
      if (networkSettings) {
        return networkSettings?.Networks?.bridge?.IPAddress ?? '0.0.0.0'
      }
      return '0.0.0.0'
    }



//在展示hostme的时候他是数组，长度多长就创建几栏
    return () => (
    <div>
        {/* 私有云显示用户存储 */}
      <div class="pr-4 pl-4" style={'width:78%;margin:auto;display:flex;justify-content:space-between;box-sizing: border-box;cursor: pointer'}>
          <div></div>
          {session_platformType === 'PRIVATE' ? (
  // 渲染的内容，当条件为真时显示
  <a  class=" w-38 h-10 text-center flex justify-around pr-1 " href="http://172.16.90.80:9090/login" style={'background:#2629d5;line-height:2.5rem;border-radius:2rem;color:inherit'}>
          
          <img src={cunchuimg} alt="" />
          <div style={'font-size:18px'}>{t('vuetitle.Userstorage')}</div>
          </a>

) : (
  // 渲染的内容，当条件为假时显示
  <div></div>
)}
        
        </div>
      <div id="competitionTag" class="relative mx-auto my-10 2xl:w-360 w-300 !flex pl-25"  style={'box-sizing: border-box'}>
       <div
          id="course"
          class="2xl:w-185 w-185 2xl:h-75 h-75 rounded-xl overflow-hidden relative shadow-md z-1 group "
          style={`background:url('${data.document?.course?.cover}')`}
        >
       
          <img src={panel} class="absolute top-0 w-full h-75 rounded-xl " />
          <div class="absolute top-15 left-15 lfcores">
            <a-typography-paragraph
              class="text-4xl text-white"
              ellipsis="ellipsis"
              content={data.document?.title}
            ></a-typography-paragraph>
{/* 修改后 */}
{/* <a-typography-paragraph
              class="text-4xl text-white"
              ellipsis="ellipsis"
              content={course_page?.title}
            ></a-typography-paragraph> */}

            {/* <p class="text-xl w-80 " style="font-size:53px; font-weight:bold">Linux</p> */}
            <a-divider style="border-color: #fff; width:20rem "  ></a-divider>
            <p class="text-xl w-80">{data.document?.description
}</p>
          </div>
          {/*弹出导航*/}
          <div
            // class="absolute bottom-0 flex items-center w-full transform translate-y-full cursor-pointer duration-400 h-25 group-hover:translate-y-0"
            style="background:rgba(69,69,69,.5)"
            onClick={() => {
              gotoChapter()
            }}
          >
            <a-row align="middle" class="h-full pl-3" gutter={[14, 14]}>
              {/* <a-col>
                <div class="text-3rem">{t('competition.continueCourse')}</div>
              </a-col> */}
              {/* <a-col>
                <i class="i-material-symbols:play-circle-rounded w-10 h-10 block"></i>
              </a-col> */}
            </a-row>
          </div>
          {/*导航 end*/}
        </div>

        <div
          id="instance"
          class="2xl:w-250 w-200 h-75 shadow-md  bg-white rounded-xl  z-2 top-0  flex justify-between"
          style="background-color:#fafafa;"
        >
          
          {/* 左右切换列表 */}
          <div class="z-3 rounded-l-xl w-60 " style="background-color:#24272b">
            {/* 实例列表 */}
            <a-row class="cursor-pointer rounded-l-xl w-30">
              {hostname.value.length > 0 &&
                hostname.value.map((name: string, index: number) => {
                  return (
                    <a-col
                      class={[
                        'w-full h-15 flex items-center justify-center ',
                        index === 0 && 'rounded-tl-xl',
                        index === 4 && 'rounded-bl-xl',
                        name === data.selectHostname ? 'active text-white' : 'normal text-gray-600'
                      ]}
                      onClick={() => {
                        data.selectHostname = name
                      }}
                    >
                      <span>{name}</span>
                    </a-col>
                  )
                })}
            </a-row>
            
          </div>
          {/* 实例介绍 */}
          <div  style={`background:url(${masterimg});background-repeat: no-repeat; background-size: cover`}>
          <div class="pt-3 pl-2  w-2/5 z-30" style="background-color:#1b1f24">
            
            <div style={'border-bottom: 1px solid #5c5c5d;color:#b3c8d9; padding-bottom: 0.6rem; font-weight: 600; font-size:3rem '} class="text-4xl text-gray-600  !text-white  ">{data.selectHostname}master</div>
           
    
          {/* <a-col>
            <a-tag bordered={false} color={currentSelectContainer.value?.State === 'running' ? 'green' : 'red'}>
              {currentSelectContainer.value?.State}
            </a-tag>
          </a-col> */}
   
        {/* <a-divider></a-divider> */}

        <a-row class="text-gray-700">
          {/* <a-col span={24}>
            <a-row gutter={[1, 2]}>
              <a-col span={24}>
                <div class="text-xl mb-2 mt-2" style="color:#b3c8d9">INSTANCE_ID</div>
              </a-col>
              <a-col span={24}>
                <div >
                  {currentSelectContainer.value?.Id && currentSelectContainer.value.Id.slice(0, 12)}
                </div>
              </a-col>
            </a-row>
          </a-col> */}
          <a-col span={24}>
            <a-row gutter={[1, 2]}>
              <a-col span={24}>
                <div class="text-xl mb-2 mt-2" style="color:#b3c8d9">{session_platformType}_ADDRESS</div>
              </a-col>
              <a-col span={24}>
                <div >
                  {currentSelectContainer.value?.Id && currentSelectContainer.value.Id.slice(0, 12)}
                </div>
              </a-col>
            </a-row>
          </a-col>
          <a-col span={24}>
            <a-row>
              <a-col span={24}>
                <div class="text-xl mb-2" style="color:#b3c8d9">IMAGE_NAME</div>
              </a-col>
              <a-col span={24}>
                <div >{currentSelectContainer.value?.Image}</div>
              </a-col>
            </a-row>
          </a-col>

          <a-col span={24}>
            <a-row>
              <a-col span={24}>
                <div class="text-xl mb-2" style="color:#b3c8d9">CONTAINER_STATUS</div>
              </a-col>
              <a-col span={24}>
                <div >{currentSelectContainer.value?.State}</div>
              </a-col>
            </a-row>
          </a-col>

          <a-col span={24}>
            <a-row>
              <a-col span={24}>
                <div class="text-xl mb-2" style="color:#b3c8d9">IP_ADDRESS</div>
              </a-col>
            
                <div  style="color:#b3c8d9">{getIPAddress(currentSelectContainer.value?.NetworkSettings)}</div>
            
            </a-row>
          </a-col>
        </a-row>
      </div>

      <div class="relative overflow-hidden rounded-r-xl" style="background-color:#1b1f24">
        {/* <img src={linuxImage} class="absolute mt-4" /> */}
        {/* <img src={masterimg}  alt="" /> */}
      </div>
          </div>
          <div>
            {/* 左右切换的列表 */}
       {/* <a-tabs v-model:activeKey={activeKey}  tab-position={tabPosition} animated>
        <a-tab-pane key="1" tab="Tab 1">Content of Tab 1</a-tab-pane>
        <a-tab-pane key="2" tab="Tab 2">Content of Tab 2</a-tab-pane>
        <a-tab-pane key="3" tab="Tab 3">Content of Tab 3</a-tab-pane>
       </a-tabs> */}
      </div>
    
          
          {/* 删除会话 */}
          <div

            class="absolute flex items-center justify-center w-20 h-20 bg-red-500 cursor-pointer rounded-xl -right-1 z-3 top-5 mr-37"
            onClick={deleteAllContainer}
          >
            <img style={'transform: scale(0.8)'} src={deleteImage} alt="" />
          </div>
          
        </div>
        
        {/* 按钮组 */}
        <div
          id="button"
          class=" relative flex items-center justify-center space-x-20   top-38 z-3 right-39  "
        >
          {currentSelectContainer.value?.State != 'running' ? (
        // 启动停止实例
         <div>
          <img style={'cursor: pointer;transform: scale(1.5)'} src={`${startimg}`}  onClick={() => {
                changeContainerState('start')
              }} alt="" />
             {/* <a-button
              class="w-37.5 h-12.5"
              type="primary"
              onClick={() => {
                changeContainerState('start')
              }}
              v-slots={{
                icon: () => <i class="i-material-symbols:play-circle w-5 h-5 bg-gray-700"></i>
              }}
            >
              {t('competition.button_startAllInstances')}
            </a-button> */}
         </div>
          ) : (
           <div>
             <img style={'cursor: pointer;transform: scale(1.5)'} src={`${stoptimg}`}   onClick={() => {
                changeContainerState('stop')
              }}
             alt="" />
             {/* <a-button
              class="w-37.5 h-12.5 flex items-center justify-center bg-red-600 text-white"
              type="primary"
              onClick={() => {
                changeContainerState('stop')
              }}
              v-slots={{
                icon: () => <i class="i-mdi:stop-circle-outline w-5 h-5  block"></i>
              }}
            >
              {t('competition.button_stopAllInstances')}
            </a-button> */}
           </div>
          )}
     {/* 刷新实例 */}
        <div>
        
        <img style={'cursor: pointer;transform: scale(1.5)'} src={`${reflushimg}`}  
               alt=""  onClick={() => {
                refetchContainers()
              }} />
        {/* <a-button
            class="w-37.5 h-12.5 flex items-center justify-center text-white"
            style={'background-color: #bbd5cb'}
            v-slots={{
              icon: () => <i class="i-ic:outline-sync w-5 h-5 block"></i>
            }}
            onClick={() => {
              refetchContainers()
            }}
          >
            {t('competition.button_reflush')}
          </a-button> */}
        </div>
        </div>
      </div>
     
      
    </div>
   
    )
  }
})
